<template>
    <view class="chat-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <view class="back-btn" @click="backToList" v-if="currentSession">
                <uni-icons type="left" size="24" />
            </view>
            <view class="title">
                {{ currentSession ? currentSession.user?.nickname || '聊天' : '客服中心' }}
                </view>
            <view class="connection-status">
                <view class="status-indicator" :class="{ 'connected': wsConnected, 'disconnected': !wsConnected }"></view>
                <text class="status-text">{{ wsConnected ? '已连接' : '未连接' }}</text>
            </view>
            <view class="right-actions">
                <uni-icons type="sound" size="24" :color="soundEnabled ? '#1976d2' : '#999'" @click="toggleSound" />
                <uni-icons v-if="!currentSession" type="plusempty" size="24" color="#1976d2" @click="createNewSession" />
            </view>
        </view>

        <!-- 会话列表 -->
        <view class="session-list" v-if="!currentSession">
            <view class="session-empty" v-if="sessions.length === 0">
                <image src="/static/images/empty-chat.png" mode="aspectFit" class="empty-image"></image>
                <text class="empty-text">暂无会话记录</text>
                <button class="start-btn" @tap="createNewSession">开始新会话</button>
            </view>
            
            <view class="new-session-banner" v-else>
                <button class="new-session-btn" @tap="createNewSession">
                    <uni-icons type="plusempty" size="20" color="#ffffff" />
                    <text>发起新会话</text>
                </button>
            </view>
            
            <view class="session-item" v-for="session in sessions" :key="session.sessionId" @tap="selectSession(session)">
                <view class="session-avatar">
                    <image :src="'/static/logo.png'" mode="aspectFill"></image>
                    <view :class="['status-dot', getStatusClass(session.sessionStatus)]"></view>
                </view>
                <view class="session-content">
                    <view class="session-top">
                        <text class="session-type">{{ session.sessionType === 'HUMAN' ? '人工客服' : 'AI客服' }}</text>
                        <text class="session-time">{{ formatTime(session.lastTime) }}</text>
                    </view>
                    <view class="session-bottom">
                        <text class="last-message">{{ session.lastMessage || '暂无消息' }}</text>
                        <view class="status-tag" :class="getStatusClass(session.sessionStatus)">
                            {{ getStatusText(session.sessionStatus) }}
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 聊天界面 -->
        <view class="chat-interface" v-else>
            <!-- 聊天头部 -->
            <view class="chat-header">
                <view class="header-left" @tap="backToList">
                    <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
                </view>
                <view class="header-center">
                    <text class="session-title">{{ currentSession.sessionType === 'HUMAN' ? '人工客服' : 'AI客服' }}</text>
                    <text class="session-status-text">{{ getStatusText(currentSession.sessionStatus) }}</text>
                </view>
                <view class="header-right">
                    <text class="end-btn" @tap="showEndDialog" v-if="currentSession.sessionStatus === 'ACTIVE'">结束</text>
                </view>
            </view>

            <!-- 消息列表 -->
            <scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" @scrolltoupper="loadMoreMessages" scroll-with-animation>
                <view class="loading-more" v-if="loading">
                    <uni-load-more status="loading" :content-text="{ contentdown: '加载更多' }"></uni-load-more>
                </view>
                
                <view class="message-date" v-if="messages.length > 0">
                    {{ formatMessageDate(messages[0].createTime) }}
                </view>
                
                <view class="message-item" v-for="(message, index) in messages" :key="message.id">
                    <view class="message-date" v-if="index > 0 && shouldShowDate(messages[index-1].createTime, message.createTime)">
                        {{ formatMessageDate(message.createTime) }}
                    </view>
                    
                    <view :class="['message-wrapper', message.senderType === 'USER' ? 'message-right' : 'message-left']">
                        <image class="message-avatar" :src="message.senderType === 'USER' ? '/static/logo.png' : (currentSession.sessionType === 'HUMAN' ? '/static/logo.png' : '/static/logo.png')" mode="aspectFill"></image>
                        <view class="message-bubble">
                            <text class="message-text">{{ message.content }}</text>
                        </view>
                    </view>
                    <text class="message-time" :class="message.senderType === 'USER' ? 'time-right' : 'time-left'">{{ formatMessageTime(message.createTime) }}</text>
                </view>
                
                <view class="message-status" v-if="currentSession.sessionStatus === 'PENDING'">
                    <view class="status-info">
                        <uni-icons type="info" size="16" color="#1976d2"></uni-icons>
                        <text>正在等待客服接入，请稍候...</text>
                    </view>
                </view>
                
                <view class="message-status" v-if="currentSession.sessionStatus === 'ENDED'">
                    <view class="status-info">
                        <uni-icons type="closeempty" size="16" color="#ff3b30"></uni-icons>
                        <text>会话已结束</text>
                    </view>
                </view>
            </scroll-view>

            <!-- 输入区域 -->
            <view class="input-area" v-if="currentSession.sessionStatus === 'ACTIVE'">
                <view class="input-wrapper">
                    <input class="message-input" v-model="inputMessage" placeholder="请输入消息" @confirm="sendMessage" :disabled="currentSession.sessionStatus !== 'ACTIVE'" cursor-spacing="12" />
                    <view class="input-actions">
                        <uni-icons type="image" size="24" color="#666" @click="chooseImage"></uni-icons>
                        <uni-icons type="paperplane-filled" size="24" color="#1976d2" @click="sendMessage" v-if="inputMessage.trim()"></uni-icons>
                    </view>
                </view>
            </view>

            <!-- 评价区域 -->
            <view class="evaluation-area" v-if="currentSession.sessionStatus === 'ENDED' && !currentSession.rating">
                <view class="evaluation-card">
                    <text class="evaluation-title">服务评价</text>
                    <text class="evaluation-desc">您对本次服务满意吗？</text>
                    
                    <view class="rating-stars">
                        <text v-for="i in 5" :key="i" 
                              :class="['star', i <= rating ? 'active' : '']"
                              @tap="setRating(i)">★</text>
                    </view>
                    
                    <textarea class="comment-input" v-model="comment" placeholder="请输入您的建议和反馈（选填）" />
                    
                    <button class="submit-btn" @tap="submitEvaluation">提交评价</button>
                </view>
            </view>
        </view>

        <!-- 创建会话选择弹窗 -->
        <uni-popup ref="sessionTypePopup" type="bottom">
            <view class="popup-content">
                <view class="popup-title">选择会话类型</view>
                <view class="popup-options">
                    <view class="option-item" @tap="createSession('AI')">
                        <image src="/static/logo.png" mode="aspectFill" class="option-icon"></image>
                        <text class="option-text">AI客服</text>
                    </view>
                    <view class="option-item" @tap="createSession('HUMAN')">
                        <image src="/static/logo.png" mode="aspectFill" class="option-icon"></image>
                        <text class="option-text">人工客服</text>
                    </view>
                </view>
                <view class="popup-cancel" @tap="closeSessionTypePopup">取消</view>
            </view>
        </uni-popup>

        <!-- 结束会话对话框 -->
        <uni-popup ref="endDialog" type="dialog">
            <uni-popup-dialog
                title="结束会话"
                content="确定要结束当前会话吗？"
                :before-close="true"
                @confirm="endSession"
                @close="closeEndDialog"
            />
        </uni-popup>
    </view>
</template>

<script>
import chatApi from '@/api/chat';
import websocket from '@/utils/websocket';
import { formatTime } from '@/utils/date';

export default {
    data() {
        return {
            sessions: [],
            currentSession: null,
            messages: [],
            inputMessage: '',
            rating: 0,
            comment: '',
            scrollTop: 0,
            page: 1,
            pageSize: 20,
            loading: false,
            soundEnabled: true,
            wsConnected: false,
            reconnecting: false,
            sounds: {
                messageReceived: null,
                messageSent: null,
                notification: null,
                click: null,
                welcome: null,
                alert: null
            },
            userInteracted: false
        };
    },

    mounted() {
        // 检测用户交互
        if (typeof document !== 'undefined') {
            document.addEventListener('click', this.handleUserInteraction);
            document.addEventListener('touchstart', this.handleUserInteraction);
            document.addEventListener('keydown', this.handleUserInteraction);
        }
        
        const userInfo = uni.getStorageSync('userInfo');
        console.log('聊天页onLoad获取到的用户信息:', JSON.stringify(userInfo));
        if (!userInfo || !userInfo.userId) {
            console.error('未找到有效的用户信息, userInfo:', JSON.stringify(userInfo));
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            setTimeout(() => {
                uni.reLaunch({
                    url: '/pages/login/login'
                });
            }, 1500);
            return;
        }
        
        console.log('聊天页准备初始化WebSocket和加载会话...');
        this.initSounds();
        this.initWebSocket().catch(err => {
            console.error('WebSocket初始化失败:', err);
        });
        this.loadSessions();
        
        // 播放欢迎语音
        setTimeout(() => {
            if (this.soundEnabled) {
                this.playSound('welcome');
            }
        }, 1000); // 延迟1秒播放，确保页面已加载
    },

    onLoad() {
        const userInfo = uni.getStorageSync('userInfo');
        console.log('聊天页onLoad获取到的用户信息:', JSON.stringify(userInfo));
        
        // 初始化音频
        this.initSounds();
        
        // 初始化WebSocket连接
        this.initWebSocket().catch(error => {
            console.error('初始化WebSocket失败:', error);
        });
    },

    onShow() {
        // 检查WebSocket连接状态，如果断开则重连
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.userId && !this.wsConnected) {
            console.log('页面显示，重新连接WebSocket');
            this.initWebSocket();
        }
    },

    onUnload() {
        // 移除事件监听
        uni.$off('websocket-connected');
        uni.$off('websocket-disconnected');
        uni.$off('websocket-error');
        uni.$off('websocket-timeout');
        uni.$off('newMessage');
        uni.$off('systemMessage');
        uni.$off('transferMessage');
        
        // 清理音频资源
        this.clearSounds();
    },

    beforeDestroy() {
        // 移除用户交互检测
        if (typeof document !== 'undefined') {
            document.removeEventListener('click', this.handleUserInteraction);
            document.removeEventListener('touchstart', this.handleUserInteraction);
            document.removeEventListener('keydown', this.handleUserInteraction);
        }
        
        // 移除事件监听
        uni.$off('websocket-connected');
        uni.$off('websocket-disconnected');
        uni.$off('websocket-error');
        uni.$off('websocket-timeout');
        uni.$off('new-chat-message');
        uni.$off('system-message');
        uni.$off('transfer-message');
        uni.$off('session-accepted');
        uni.$off('session-rejected');
        uni.$off('session-ended');
        uni.$off('websocket-message');
        
        // 释放音频资源
        if (this.sounds.messageReceived) {
            try {
                this.sounds.messageReceived.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.messageSent) {
            try {
                this.sounds.messageSent.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.notification) {
            try {
                this.sounds.notification.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.click) {
            try {
                this.sounds.click.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        
        // 断开WebSocket连接
        // 注意：不要断开连接，因为其他页面可能也需要使用
        // websocket.disconnect();
        // this.wsConnected = false;
    },

    methods: {
        initSounds() {
            try {
                // 创建音频对象
                this.sounds.messageReceived = uni.createInnerAudioContext();
                this.sounds.messageReceived.src = '/static/sounds/alter.mp3';
                this.sounds.messageReceived.preload = true;
                
                this.sounds.messageSent = uni.createInnerAudioContext();
                this.sounds.messageSent.src = '/static/sounds/success.mp3';
                this.sounds.messageSent.preload = true;
                
                this.sounds.notification = uni.createInnerAudioContext();
                this.sounds.notification.src = '/static/sounds/notification.mp3';
                this.sounds.notification.preload = true;
                
                this.sounds.click = uni.createInnerAudioContext();
                this.sounds.click.src = '/static/sounds/click.mp3';
                this.sounds.click.preload = true;
                
                this.sounds.welcome = uni.createInnerAudioContext();
                this.sounds.welcome.src = '/static/sounds/welcome.mp3';
                this.sounds.welcome.preload = true;
                
                this.sounds.alert = uni.createInnerAudioContext();
                this.sounds.alert.src = '/static/sounds/alert.mp3';
                this.sounds.alert.preload = true;
                
                // 从本地存储加载声音设置
                const soundSetting = uni.getStorageSync('sound_enabled');
                if (soundSetting !== undefined && soundSetting !== null) {
                    this.soundEnabled = soundSetting === 'true';
                }
                
                // 设置WebSocket客户端的声音状态
                websocket.setSoundsEnabled(this.soundEnabled);
                
                console.log('音频初始化成功，声音状态:', this.soundEnabled);
            } catch (error) {
                console.error('音频初始化失败:', error);
                this.soundEnabled = false;
            }
        },
        
        toggleSound() {
            this.soundEnabled = !this.soundEnabled;
            
            // 保存设置到本地存储
            uni.setStorageSync('sound_enabled', this.soundEnabled.toString());
            
            // 更新WebSocket客户端的声音状态
            websocket.setSoundsEnabled(this.soundEnabled);
            
            // 播放提示音以确认
            if (this.soundEnabled) {
                this.playSound('sent');
            }
            
            uni.showToast({
                title: this.soundEnabled ? '已开启声音' : '已关闭声音',
                icon: 'none'
            });
        },
        
        playSound(type) {
            if (!this.soundEnabled) return;
            
            // 在H5环境中检查用户是否已交互
            // #ifdef H5
            if (!this.userInteracted) {
                console.log('用户尚未与页面交互，跳过声音播放');
                return;
            }
            // #endif
            
            try {
                let sound;
                switch (type) {
                    case 'received':
                        sound = this.sounds.messageReceived;
                        break;
                    case 'sent':
                        sound = this.sounds.messageSent;
                        break;
                    case 'notification':
                        sound = this.sounds.notification;
                        break;
                    case 'click':
                        sound = this.sounds.click;
                        break;
                    case 'welcome':
                        sound = this.sounds.welcome;
                        break;
                    case 'alert':
                        sound = this.sounds.alert;
                        break;
                    default:
                        sound = this.sounds.messageSent;
                }
                
                if (sound) {
                    // 先停止之前的播放，避免重叠
                    try {
                        sound.stop();
                    } catch (e) {
                        // 忽略停止错误
                    }
                    
                    // 重置播放位置
                    try {
                        sound.seek(0);
                    } catch (e) {
                        // 忽略seek错误
                    }
                    
                    // 使用setTimeout延迟播放，避免连续多次播放导致的错误
                    setTimeout(() => {
                        try {
                            sound.play();
                        } catch (e) {
                            console.error('播放声音失败:', e);
                        }
                    }, 50);
                }
            } catch (error) {
                console.error('播放声音失败:', error);
            }
        },

        async initWebSocket() {
            const userInfo = uni.getStorageSync('userInfo');
            if (!userInfo || !userInfo.userId) {
                console.error('初始化WebSocket失败：未找到用户信息');
                return Promise.reject(new Error('未找到用户信息'));
            }
            
            console.log('初始化WebSocket连接，用户ID:', userInfo.userId);
            
            // 更严格地检查WebSocket连接状态
            if (websocket.isConnected) {
                console.log('WebSocket已连接，无需重新连接');
                this.wsConnected = true;
                
                // 确保消息处理器已注册
                this.setupMessageHandlers();
                return Promise.resolve(true);
            }
            
            // 如果正在连接中，等待连接完成
            if (websocket.connecting) {
                console.log('WebSocket正在连接中，等待连接完成...');
                
                // 等待连接完成或超时
                return new Promise((resolve) => {
                    const checkConnected = () => {
                        if (websocket.isConnected) {
                            this.wsConnected = true;
                            this.setupMessageHandlers();
                            resolve(true);
                            return;
                        }
                        
                        // 如果不再处于连接中状态，说明连接失败
                        if (!websocket.connecting) {
                            this.wsConnected = false;
                            resolve(false);
                            return;
                        }
                        
                        // 继续等待
                        setTimeout(checkConnected, 500);
                    };
                    
                    // 开始检查
                    checkConnected();
                });
            }
            
            // 显示连接状态
            let loadingShown = false;
            if (!this.wsConnected) {
                uni.showLoading({
                    title: '正在连接...',
                    mask: false
                });
                loadingShown = true;
            }
            
            return new Promise((resolve, reject) => {
                try {
                    // 移除旧的事件监听
                    this.removeEventListeners();
                    
                    // 添加连接状态事件监听
                    this.setupEventListeners();
                    
                    // 尝试连接
                    websocket.connect(userInfo.userId)
                        .then(() => {
                            // 添加正式的消息处理器
                            this.setupMessageHandlers();
                            
                            if (loadingShown) {
                                uni.hideLoading();
                            }
                            
                            resolve(true);
                        })
                        .catch(error => {
                            console.error('WebSocket连接失败:', error);
                            this.wsConnected = false;
                            if (loadingShown) {
                                uni.hideLoading();
                            }
                            
                            // 显示错误提示
                            uni.showToast({
                                title: '连接失败，正在重试...',
                                icon: 'none',
                                duration: 2000
                            });
                            
                            reject(error);
                            
                            // 尝试自动重连
                            this.reconnectWebSocket();
                        });
                } catch (error) {
                    console.error('初始化WebSocket过程出错:', error);
                    this.wsConnected = false;
                    if (loadingShown) {
                        uni.hideLoading();
                    }
                    reject(error);
                }
            });
        },
        
        // 设置消息处理器
        setupMessageHandlers() {
                    // 先移除旧的消息处理器，避免重复添加
                    websocket.removeMessageHandler('CHAT');
                    websocket.removeMessageHandler('SYSTEM');
                    websocket.removeMessageHandler('TRANSFER');
                    websocket.removeMessageHandler('UNREAD');
                    
            // 添加新的消息处理器
                        websocket.addMessageHandler('CHAT', this.handleChatMessage);
                        websocket.addMessageHandler('SYSTEM', this.handleSystemMessage);
                        websocket.addMessageHandler('TRANSFER', this.handleTransferMessage);
                        websocket.addMessageHandler('UNREAD', (message) => {
                            this.updateUnreadCount(message.sessionId, message.unreadCount);
                        });
        },
        
        // 设置事件监听器
        setupEventListeners() {
            // 添加连接状态事件监听
            uni.$on('websocket-connected', () => {
                console.log('WebSocket连接已建立 (Event)');
                this.wsConnected = true;
                
                // 播放连接成功音效
                if (this.soundEnabled) {
                    this.playSound('sent');
                }
            });
                    
            uni.$on('websocket-disconnected', () => {
                console.log('WebSocket连接已断开 (Event)');
                        this.wsConnected = false;
                
                // 显示断开连接提示
                uni.showToast({
                    title: '连接已断开，正在重连...',
                    icon: 'none',
                    duration: 2000
                });
                    });
                    
            uni.$on('websocket-error', (error) => {
                console.error('WebSocket错误 (Event):', error);
                this.wsConnected = false;
                    });
                    
            uni.$on('websocket-timeout', () => {
                console.error('WebSocket连接超时 (Event)');
                    this.wsConnected = false;
                
                uni.showToast({
                    title: '连接超时，正在重试...',
                    icon: 'none',
                    duration: 2000
                });
            });
        },
        
        // 移除事件监听器
        removeEventListeners() {
            uni.$off('websocket-connected');
            uni.$off('websocket-disconnected');
            uni.$off('websocket-error');
            uni.$off('websocket-timeout');
        },
        
        async reconnectWebSocket() {
            if (this.reconnecting) return;
            
            this.reconnecting = true;
            console.log('正在重新连接WebSocket...');
            
            return new Promise((resolve) => {
                setTimeout(async () => {
                    try {
                        await this.initWebSocket();
                        console.log('WebSocket重连' + (this.wsConnected ? '成功' : '失败'));
                        resolve(this.wsConnected);
                    } catch (err) {
                        console.error('WebSocket重连错误:', err);
                        resolve(false);
                    } finally {
                        this.reconnecting = false;
                    }
                }, 1000);
            });
        },

        async loadSessions() {
            try {
                uni.showLoading({ title: '加载中...' });
                const res = await chatApi.getSessions({
                    current: 1,
                    pageSize: 20
                });
                
                console.log('获取到的会话列表:', res);
                if (res.data && res.data.records) {
                    this.sessions = res.data.records;
                } else {
                    this.sessions = [];
                }
                uni.hideLoading();
            } catch (error) {
                console.error('加载会话列表失败:', error);
                uni.hideLoading();
                uni.showToast({
                    title: '加载会话列表失败',
                    icon: 'none'
                });
            }
        },

        async selectSession(session) {
            this.playSound('click');
            console.log('选择会话:', session);
            this.currentSession = session;
            this.messages = [];
            this.page = 1;
            this.loading = true;
            
            try {
                await this.loadMessages();
            } finally {
                this.loading = false;
            }
        },

        async loadMessages() {
            if (!this.currentSession) return;
            
            try {
                const res = await chatApi.getSessionMessages(this.currentSession.sessionId);
                console.log('获取到的消息:', res);
                
                if (res.data) {
                    // 按时间排序
                    const sortedMessages = [...res.data].sort((a, b) => 
                        new Date(a.createTime) - new Date(b.createTime)
                    );
                    
                    this.messages = sortedMessages;
                    this.scrollToBottom();
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                uni.showToast({
                    title: '加载消息失败',
                    icon: 'none'
                });
            }
        },

        async loadMoreMessages() {
            if (this.loading || !this.currentSession) return;
            if (this.messages.length < this.page * this.pageSize) return;
            
            this.loading = true;
            this.page++;
            
            try {
                const res = await chatApi.loadMessages(
                    this.currentSession.sessionId,
                    this.page,
                    this.pageSize
                );
                
                if (res.data && res.data.length > 0) {
                    // 将新消息添加到前面
                    const sortedMessages = [...res.data].sort((a, b) => 
                        new Date(a.createTime) - new Date(b.createTime)
                    );
                    
                    this.messages = [...sortedMessages, ...this.messages];
                }
            } catch (error) {
                console.error('加载更多消息失败:', error);
            } finally {
                this.loading = false;
            }
        },

        async sendMessage() {
            if (!this.inputMessage.trim() || !this.currentSession) return;
            if (this.currentSession.sessionStatus !== 'ACTIVE') {
                uni.showToast({
                    title: '当前会话不可发送消息',
                    icon: 'none'
                });
                return;
            }
            
            // 播放点击音效
            this.playSound('click');
            
            const content = this.inputMessage.trim();
            this.inputMessage = '';
            
            // 先添加到本地消息列表，乐观更新UI
            const tempMessage = {
                id: 'temp-' + Date.now(),
                sessionId: this.currentSession.sessionId,
                content: content,
                senderType: 'USER',
                createTime: new Date().toISOString(),
                messageType: 'TEXT',
                status: 'SENDING' // 添加状态标记
            };
            
            this.messages.push(tempMessage);
            this.scrollToBottom();
            
            try {
                // 检查WebSocket是否已连接
                if (!this.wsConnected) {
                    console.log('WebSocket未连接，尝试重新连接...');
                    await this.reconnectWebSocket();
                    
                    if (!this.wsConnected) {
                        throw new Error('无法连接到服务器，请稍后再试');
                    }
                }
                
                // 通过WebSocket发送消息
                const message = {
                    type: 'CHAT',
                    sessionId: this.currentSession.sessionId,
                    content: content,
                    messageType: 'TEXT',
                    status: 'SENT',
                    timestamp: new Date().toISOString()
                };
                
                const sent = await websocket.sendMessage(message);
                
                if (sent) {
                    // 更新临时消息状态为已发送
                    const tempMsg = this.messages.find(msg => msg.id === tempMessage.id);
                    if (tempMsg) {
                        tempMsg.status = 'SENT';
                }
                
                    // 播放发送成功音效
                    this.playSound('sent');
                
                // 更新会话列表中的最后一条消息
                this.updateSessionLastMessage(this.currentSession.sessionId, content);
                } else {
                    throw new Error('消息发送失败');
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                
                // 检查是否是AI模型相关错误
                if (error.message && (
                    error.message.includes('Failed to communicate with Ollama API') || 
                    error.message.includes('AI模型暂时不可用')
                )) {
                    console.warn('AI模型服务暂时不可用，但消息已发送');
                    
                    // 更新临时消息状态为已发送
                    const tempMsg = this.messages.find(msg => msg.id === tempMessage.id);
                    if (tempMsg) {
                        tempMsg.status = 'SENT';
                    }
                    
                    // 播放发送成功音效
                    this.playSound('sent');
                    
                    // 显示友好提示
                    uni.showToast({
                        title: '消息已发送，但AI响应可能延迟',
                        icon: 'none',
                        duration: 2000
                    });
                
                // 更新会话列表中的最后一条消息
                this.updateSessionLastMessage(this.currentSession.sessionId, content);
                    
                    return;
                }
                
                // 更新临时消息状态为失败
                const tempMsg = this.messages.find(msg => msg.id === tempMessage.id);
                if (tempMsg) {
                    tempMsg.status = 'FAILED';
                }
                
                // 播放错误提示音
                this.playSound('notification');
                
                uni.showToast({
                    title: '发送消息失败，请重试',
                    icon: 'none'
                });
            }
        },
        
        async chooseImage() {
            try {
                const res = await uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera']
                });
                
                if (res.tempFilePaths && res.tempFilePaths.length > 0) {
                    await this.uploadAndSendImage(res.tempFilePaths[0]);
                }
            } catch (error) {
                console.error('选择图片失败:', error);
            }
        },
        
        async uploadAndSendImage(filePath) {
            uni.showLoading({ title: '发送图片中...' });
            
            try {
                // 上传图片逻辑，需要后端支持
                // 成功后通过WebSocket发送图片消息
                uni.showToast({
                    title: '图片发送功能暂未实现',
                    icon: 'none'
                });
            } catch (error) {
                console.error('发送图片失败:', error);
                uni.showToast({
                    title: '发送图片失败',
                    icon: 'none'
                });
            } finally {
                uni.hideLoading();
            }
        },

        handleChatMessage(message) {
            console.log('收到聊天消息:', message);
            if (message.sessionId === this.currentSession?.sessionId) {
                // 防止重复添加消息
                if (!this.messages.some(msg => msg.id === message.id)) {
                    this.messages.push(message);
                    this.scrollToBottom();
                    
                    // 如果是对方发送的消息，播放提示音
                    if (message.senderType !== 'USER') {
                        this.playSound('received');
                }
                }
            } else {
                // 如果不是当前会话的消息，更新未读计数并播放提示音
                this.playSound('notification');
            }
            
            // 更新会话列表
            this.updateSessionLastMessage(message.sessionId, message.content);
        },

        handleSystemMessage(message) {
            console.log('收到系统消息:', message);
            if (message.sessionId === this.currentSession?.sessionId) {
                uni.showToast({
                    title: message.content,
                    icon: 'none'
                });
                
                // 处理会话状态更新
                if (message.action === 'SESSION_STATUS_CHANGE') {
                    this.updateSessionStatus(message.sessionId, message.status);
                }
            }
        },

        handleTransferMessage(message) {
            console.log('收到转接消息:', message);
            if (message.sessionId === this.currentSession?.sessionId) {
                uni.showToast({
                    title: '会话已转接',
                    icon: 'none'
                });
                
                // 更新会话状态
                this.updateSessionStatus(message.sessionId, 'PENDING');
            }
        },
        
        updateSessionLastMessage(sessionId, content) {
            const session = this.sessions.find(s => s.sessionId === sessionId);
            if (session) {
                session.lastMessage = content;
                session.lastTime = new Date().toISOString();
            } else {
                // 会话不在列表中，可能是新会话，刷新列表
                this.loadSessions();
            }
        },
        
        updateSessionStatus(sessionId, status) {
            if (this.currentSession && this.currentSession.sessionId === sessionId) {
                this.currentSession.sessionStatus = status;
            }
            
            const session = this.sessions.find(s => s.sessionId === sessionId);
            if (session) {
                session.sessionStatus = status;
            }
        },
        
        updateUnreadCount(sessionId, count) {
            const session = this.sessions.find(s => s.sessionId === sessionId);
            if (session) {
                session.unreadCount = count;
            }
        },

        scrollToBottom() {
            setTimeout(() => {
                this.scrollTop = 999999;
            }, 100);
        },

        backToList() {
            this.playSound('click');
            this.currentSession = null;
            this.messages = [];
            this.page = 1;
            
            // 刷新会话列表
            this.loadSessions();
        },

        showEndDialog() {
            this.playSound('click');
            this.$refs.endDialog.open();
        },

        closeEndDialog() {
            this.playSound('click');
            this.$refs.endDialog.close();
        },

        async endSession() {
            try {
                await chatApi.endSession(this.currentSession.sessionId, '用户主动结束');
                this.currentSession.sessionStatus = 'ENDED';
                uni.showToast({
                    title: '会话已结束',
                    icon: 'success'
                });
            } catch (error) {
                console.error('结束会话失败:', error);
                uni.showToast({
                    title: '结束会话失败',
                    icon: 'none'
                });
            }
        },

        setRating(rating) {
            this.rating = rating;
        },

        async submitEvaluation() {
            if (this.rating === 0) {
                uni.showToast({
                    title: '请选择评分',
                    icon: 'none'
                });
                return;
            }

            try {
                // 直接传递评分和评价内容参数
                await chatApi.submitEvaluation(
                    this.currentSession.sessionId,
                    this.rating,
                    this.comment
                );
                uni.showToast({
                    title: '评价成功',
                    icon: 'success'
                });
                this.currentSession.rating = this.rating;
                setTimeout(() => {
                    this.backToList();
                }, 1500);
            } catch (error) {
                console.error('提交评价失败:', error);
                uni.showToast({
                    title: '提交评价失败',
                    icon: 'none'
                });
            }
        },
        
        createNewSession() {
            this.playSound('click');
            this.$refs.sessionTypePopup.open();
        },
        
        closeSessionTypePopup() {
            this.playSound('click');
            this.$refs.sessionTypePopup.close();
        },
        
        async createSession(type) {
            this.playSound('click');
            this.$refs.sessionTypePopup.close();
            
            try {
                uni.showLoading({ title: '创建会话中...' });
                
                // Make sure WebSocket is connected before creating session
                if (!this.wsConnected) {
                    // Try reconnect
                    console.log('WebSocket未连接，尝试重新连接...');
                    await this.reconnectWebSocket();
                    
                    if (!this.wsConnected) {
                        throw new Error('无法连接到服务器，请稍后再试');
                    }
                }
                
                // 发起创建会话请求
                const res = await chatApi.createSession(type);
                
                if (res.data) {
                    console.log('会话创建成功:', res.data);
                    
                    // 将新会话添加到会话列表的顶部
                    this.sessions.unshift(res.data);
                    
                    // 选择并进入新会话
                    await this.selectSession(res.data);
                    
                    // 播放成功音效和欢迎音效
                    this.playSound('sent');
                    setTimeout(() => {
                        this.playSound('welcome');
                    }, 500);
                    
                    // 显示会话创建成功提示
                    const sessionTypeName = type === 'HUMAN' ? '人工客服' : 'AI客服';
                    uni.showToast({
                        title: `已连接${sessionTypeName}`,
                        icon: 'success',
                        duration: 2000
                    });
                    
                    // 如果是人工客服，显示等待提示
                    if (type === 'HUMAN') {
                        setTimeout(() => {
                            if (this.currentSession && this.currentSession.sessionStatus === 'PENDING') {
                            uni.showToast({
                                    title: '正在等待客服接入，请稍候...',
                                icon: 'none',
                                duration: 3000
                            });
                            }
                        }, 2000);
                        
                        // 自动发送一条初始消息，帮助客服了解用户需求
                        setTimeout(() => {
                            if (this.currentSession && this.currentSession.sessionId === res.data.sessionId) {
                                const initialMessage = {
                                    type: 'CHAT',
                                    sessionId: res.data.sessionId,
                                    content: '您好，我需要咨询一些问题',
                                    messageType: 'TEXT'
                                };
                                
                                // 添加到本地消息列表
                                const tempMessage = {
                                    id: 'temp-' + Date.now(),
                                    sessionId: res.data.sessionId,
                                    content: initialMessage.content,
                                    senderType: 'USER',
                                    createTime: new Date().toISOString(),
                                    messageType: 'TEXT',
                                    status: 'SENDING'
                                };
                                
                                this.messages.push(tempMessage);
                                this.scrollToBottom();
                                
                                // 发送消息
                                websocket.sendMessage(initialMessage)
                                    .then(() => {
                                        // 更新临时消息状态
                                        const msg = this.messages.find(m => m.id === tempMessage.id);
                                        if (msg) {
                                            msg.status = 'SENT';
                                        }
                                    })
                                    .catch(error => {
                                        console.error('发送初始消息失败:', error);
                                        const msg = this.messages.find(m => m.id === tempMessage.id);
                                        if (msg) {
                                            msg.status = 'FAILED';
                                        }
                                    });
                            }
                        }, 1000);
                    } else {
                        // 如果是AI客服，状态通常会立即变为ACTIVE
                        // 可以添加一条欢迎消息
                        setTimeout(() => {
                            if (this.currentSession && this.currentSession.sessionId === res.data.sessionId) {
                                // 模拟接收到AI的欢迎消息
                                const welcomeMessage = {
                                    id: 'ai-welcome-' + Date.now(),
                                    sessionId: res.data.sessionId,
                                    content: '您好，我是AI客服助手，请问有什么可以帮助您的？',
                                    senderType: 'SERVICE',
                                    createTime: new Date().toISOString(),
                                    messageType: 'TEXT'
                                };
                                
                                this.messages.push(welcomeMessage);
                                this.scrollToBottom();
                                this.playSound('received');
                            }
                        }, 800);
                    }
                } else {
                    throw new Error('创建会话失败，请稍后重试');
                }
            } catch (error) {
                console.error('创建会话失败:', error);
                // 播放错误提示音
                this.playSound('notification');
                uni.showToast({
                    title: error.message || '创建会话失败',
                    icon: 'none',
                    duration: 3000
                });
            } finally {
                uni.hideLoading();
            }
        },

        getStatusText(status) {
            const statusMap = {
                'PENDING': '等待接入',
                'ACTIVE': '进行中',
                'ENDED': '已结束',
                'REJECTED': '已拒绝'
            };
            return statusMap[status] || status;
        },
        
        getStatusClass(status) {
            const classMap = {
                'PENDING': 'pending',
                'ACTIVE': 'active',
                'ENDED': 'ended',
                'REJECTED': 'rejected'
            };
            return classMap[status] || '';
        },
        
        formatTime,
        
        formatMessageDate(time) {
            if (!time) return '';
            
            const date = new Date(time);
            const now = new Date();
            const isToday = date.toDateString() === now.toDateString();
            const isYesterday = new Date(now - 86400000).toDateString() === date.toDateString();
            
            if (isToday) {
                return '今天';
            } else if (isYesterday) {
                return '昨天';
            } else {
                return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
            }
        },
        
        formatMessageTime(time) {
            if (!time) return '';
            
            const date = new Date(time);
            return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        },
        
        shouldShowDate(prevTime, currTime) {
            if (!prevTime || !currTime) return false;
            
            const prevDate = new Date(prevTime);
            const currDate = new Date(currTime);
            
            return prevDate.toDateString() !== currDate.toDateString();
        },

        // 处理用户交互
        handleUserInteraction() {
            this.userInteracted = true;
            // 同时更新WebSocket客户端的状态
            if (websocket) {
                websocket.setUserInteracted(true);
            }
        }
    }
};
</script>

<style lang="scss">
.chat-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f7f7fa;
}

/* 导航栏样式 */
.nav-bar {
    height: 90rpx;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    border-bottom: 1rpx solid #eeeeee;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 100;
}

.back-btn {
    width: 70rpx;
    height: 70rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

.title {
    font-size: 34rpx;
    font-weight: 600;
    color: #333333;
}

.connection-status {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
}

.status-indicator {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    margin-right: 10rpx;
    
    &.connected {
        background-color: #4caf50;
        box-shadow: 0 0 10rpx rgba(76, 175, 80, 0.5);
    }
    
    &.disconnected {
        background-color: #f44336;
        box-shadow: 0 0 10rpx rgba(244, 67, 54, 0.5);
    }
}

.status-text {
    font-size: 24rpx;
    color: #666;
}

.right-actions {
    display: flex;
    align-items: center;
}

.create-btn {
    width: 70rpx;
    height: 70rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

/* 会话列表样式 */
.session-list {
    flex: 1;
    padding: 20rpx 30rpx;
    overflow-y: auto;
}

.session-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 70vh;
}

.empty-image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
}

.empty-text {
    font-size: 30rpx;
    color: #999999;
    margin-bottom: 40rpx;
}

.start-btn {
    width: 300rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #1976d2;
    color: #ffffff;
    border-radius: 40rpx;
    font-size: 30rpx;
    font-weight: 500;
    box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.2);
}

.new-session-banner {
    margin-bottom: 30rpx;
    padding: 10rpx 0;
}

.new-session-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    background-color: #1976d2;
    color: #ffffff;
    border-radius: 16rpx;
    font-size: 30rpx;
    font-weight: 500;
    box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.2);
}

.new-session-btn text {
    margin-left: 10rpx;
}

.session-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    margin-bottom: 20rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
    transition: all 0.3s ease;
}

.session-item:active {
    transform: scale(0.98);
    background-color: #f8f8f8;
}

.session-avatar {
    position: relative;
    margin-right: 20rpx;
}

.session-avatar image {
    width: 90rpx;
    height: 90rpx;
    border-radius: 45rpx;
    background-color: #f0f0f0;
}

.status-dot {
    position: absolute;
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    right: 0;
    bottom: 0;
    border: 3rpx solid #ffffff;
}

.status-dot.active {
    background-color: #4caf50;
}

.status-dot.pending {
    background-color: #ff9800;
}

.status-dot.ended {
    background-color: #9e9e9e;
}

.status-dot.rejected {
    background-color: #f44336;
}

.session-content {
    flex: 1;
    overflow: hidden;
}

.session-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8rpx;
}

.session-type {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
}

.session-time {
    font-size: 24rpx;
    color: #999999;
}

.session-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.last-message {
    flex: 1;
    font-size: 26rpx;
    color: #666666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-right: 20rpx;
}

.status-tag {
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    font-size: 22rpx;
    font-weight: 500;
}

.status-tag.active {
    background-color: rgba(76, 175, 80, 0.1);
    color: #4caf50;
}

.status-tag.pending {
    background-color: rgba(255, 152, 0, 0.1);
    color: #ff9800;
}

.status-tag.ended {
    background-color: rgba(158, 158, 158, 0.1);
    color: #9e9e9e;
}

.status-tag.rejected {
    background-color: rgba(244, 67, 54, 0.1);
    color: #f44336;
}

/* 聊天界面样式 */
.chat-interface {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f2f2f7;
}

.chat-header {
    height: 90rpx;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    border-bottom: 1rpx solid #eeeeee;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.header-left, .header-right {
    width: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.header-center {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.session-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
}

.session-status-text {
    font-size: 22rpx;
    color: #999999;
    margin-top: 4rpx;
}

.end-btn {
    font-size: 28rpx;
    color: #f44336;
}

.message-list {
    flex: 1;
    padding: 20rpx 30rpx;
    overflow-y: auto;
}

.loading-more {
    padding: 20rpx 0;
    text-align: center;
}

.message-date {
    text-align: center;
    margin: 30rpx 0;
}

.message-date text {
    padding: 6rpx 16rpx;
    background-color: rgba(0, 0, 0, 0.05);
    border-radius: 20rpx;
    font-size: 24rpx;
    color: #999999;
}

.message-item {
    margin-bottom: 30rpx;
}

.message-wrapper {
    display: flex;
    align-items: flex-start;
    margin-bottom: 8rpx;
}

.message-left {
    justify-content: flex-start;
}

.message-right {
    justify-content: flex-end;
    flex-direction: row-reverse;
}

.message-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin: 0 16rpx;
    background-color: #f0f0f0;
}

.message-bubble {
    max-width: calc(100% - 130rpx);
    padding: 20rpx 24rpx;
    border-radius: 18rpx;
    position: relative;
}

.message-left .message-bubble {
    background-color: #ffffff;
    border-top-left-radius: 4rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.message-right .message-bubble {
    background-color: #1976d2;
    border-top-right-radius: 4rpx;
    box-shadow: 0 2rpx 8rpx rgba(25, 118, 210, 0.2);
}

.message-text {
    font-size: 30rpx;
    line-height: 1.5;
    word-break: break-all;
}

.message-right .message-text {
    color: #ffffff;
}

.message-left .message-text {
    color: #333333;
}

.message-time {
    font-size: 22rpx;
    color: #999999;
    margin: 4rpx 20rpx;
}

.time-right {
    text-align: right;
}

.time-left {
    text-align: left;
    margin-left: 90rpx;
}

.message-status {
    display: flex;
    justify-content: center;
    margin: 30rpx 0;
}

.status-info {
    padding: 10rpx 20rpx;
    background-color: rgba(0, 0, 0, 0.05);
    border-radius: 20rpx;
    display: flex;
    align-items: center;
}

.status-info text {
    font-size: 26rpx;
    color: #666666;
    margin-left: 10rpx;
}

.input-area {
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    border-top: 1rpx solid #eeeeee;
}

.input-wrapper {
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 20rpx;
}

.message-input {
    flex: 1;
    height: 72rpx;
    background-color: transparent;
    padding: 0 20rpx;
}

.input-actions {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

/* 评价区域样式 */
.evaluation-area {
    padding: 30rpx;
}

.evaluation-card {
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: center;
}

.evaluation-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 20rpx;
}

.evaluation-desc {
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 30rpx;
}

.rating-stars {
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
}

.star {
    font-size: 60rpx;
    color: #ddd;
    margin: 0 10rpx;
    transition: all 0.3s ease;
}

.star.active {
    color: #FFD700;
    transform: scale(1.2);
}

.comment-input {
    width: 100%;
    height: 200rpx;
    background-color: #f7f7fa;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    font-size: 28rpx;
}

.submit-btn {
    width: 80%;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    background-color: #1976d2;
    color: #ffffff;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.2);
}

/* 弹窗样式 */
.popup-content {
    width: 100%;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    padding: 30rpx;
}

.popup-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 30rpx;
    text-align: center;
}

.popup-options {
    display: flex;
    justify-content: space-around;
    padding: 20rpx 0 40rpx;
}

.option-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx;
    width: 40%;
    border-radius: 16rpx;
    transition: all 0.3s ease;
}

.option-item:active {
    background-color: #f5f5f5;
}

.option-icon {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    margin-bottom: 20rpx;
}

.option-text {
    font-size: 30rpx;
    font-weight: 500;
    color: #333333;
}

.popup-cancel {
    border-top: 1rpx solid #eeeeee;
    padding-top: 30rpx;
    text-align: center;
    font-size: 32rpx;
    color: #999999;
}

/* 消息状态样式 */
.message-item {
    &.sending .message-text {
        opacity: 0.7;
    }
    
    &.failed .message-text {
        color: #f44336;
        border: 1px solid #f44336;
    }
    
    .message-status {
        font-size: 20rpx;
        color: #999;
        margin-top: 4rpx;
    }
}
</style> 